package com.gt.wxpay.cashier.common.scheduled;


import com.gt.wxpay.cashier.domain.Result;
import com.gt.wxpay.cashier.domain.model.CashierPayment;
import com.gt.wxpay.cashier.domain.model.RefundStatusEnum;
import com.gt.wxpay.cashier.domain.model.TransactionTypeEnum;
import com.gt.wxpay.cashier.payment.application.MerchantRefundHandlerService;
import com.gt.wxpay.cashier.payment.application.PaymentService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * packageName com.gt.wxpay.cashier.common.scheduled
 *
 * @author GuoTong
 * @version JDK 8
 * @className RefundFialTryScheduled
 * @date 2024/3/25
 * @description 失败订单--结算时重试发起退款 || 定时处理商户退款
 */
@Service
public class RefundFailTryScheduled {

    private Logger logger = LoggerFactory.getLogger(OrderStatusUpdateScheduled.class);

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private MerchantRefundHandlerService merchantRefundHandlerService;

    /**
     * 商户退款触发流程---失败订单--结算时重试发起退款 |每分钟执行一次
     *
     * @param param param
     * @return ReturnT
     */
    public Result<String> handlerFailRefundOrder(String param) {
        // 当前服务器索引
        int shardIndex = 0;//XxlJobContext.getXxlJobContext().getShardIndex();
        // 总服务器数
        int shardTotal = 1;//XxlJobContext.getXxlJobContext().getShardTotal();
        try {
            // 获取失败的枚举值
            Integer merchantRefundAbnormalValue = RefundStatusEnum.ABNORMAL.getCode();
            // 获取交易类型退款
            Integer TransactionTypeValue = TransactionTypeEnum.REFUND.code();
            // 获取商户的所有退款失败的订单----重新发起退款
            List<CashierPayment> listFailOrder = paymentService.listAllByMerchantRefundFailTry(merchantRefundAbnormalValue, TransactionTypeValue);
            if (CollectionUtils.isEmpty(listFailOrder)) {
                return Result.success();
            }
            // 遍历失败的订单----重新发起退款
            for (CashierPayment payment : listFailOrder) {
                if (shardIndex != (payment.getMid() % shardTotal)) {
                    continue;
                }
                // 调用退款接口
                try {
                    merchantRefundHandlerService.refundHandler(payment);
                } catch (Exception e) {
                    logger.error("失败订单" + payment.getPaymentNo() + "--结算时重试发起退款---调用失败", e);
                }
            }

        } catch (Exception e) {
            logger.error("失败订单--结算时重试发起退款---调用失败", e);
            return Result.error("失败订单--结算时重试发起退款---调用失败");
        }
        return Result.success();
    }
}
